package utils;

import java.io.IOException;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.*;

import org.hibernate.Session;

import presentation.PresentationsBean;

import db.Album;
import db.DbUtils;

 public class AddAlbumServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String albumName = request.getParameter("album_name");
		Long parentId = null;
		if (!albumName.equals("")) {
					
			Long userId;
			Session hbSession = DbUtils.startSession();
			HttpSession session = request.getSession();
			userId = (Long)session.getAttribute("userid");
			try {
				parentId = Long.parseLong(request.getParameter("parent_id"));
			} catch (Throwable e) {
				parentId = null;
			}
			if(parentId != null) {
				DbUtils.addAlbum(hbSession, albumName, parentId);
			} else {
				DbUtils.addAlbum(hbSession, userId, albumName);
			}
			
			hbSession.flush();
			hbSession.getTransaction().commit();
			
			if(parentId != null) {
				Album album = DbUtils.findAlbum(hbSession, parentId);
				List<Album> childAlbums = album.getChildAlbums();
				session.setAttribute("user_albums", childAlbums);
			} else {
				List<Album> userAlbums = PresentationsBean.getTopLevelAlbumsByUser(userId, 1);
				session.setAttribute("user_albums", userAlbums);
			}
		}
		
		// I don't close the session because the referer may need to lazy load something
		String referer = request.getParameter("refer");
		if(parentId != null) {
			response.sendRedirect(referer + "?album_id=" + parentId);
		} else {
			response.sendRedirect(referer + "?root=true");
		}
	}   	  	   
}